package org.footito.android.tools;

import android.content.Context;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;

public class HomeWakeLock {
	static final String TAG = "Footito";
	static HomeWakeLock instance;
	static PowerManager powerManager;
	protected static WakeLock wakeLock = null;

	public static synchronized HomeWakeLock getInstance() {
		if (instance == null)
			instance = new HomeWakeLock();
		return instance;
	}

	public void acquireLock(Context context) {
		powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
		if (wakeLock == null) {
			Log.w(TAG, "new Wakelock");
			wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "BWL");
			wakeLock.acquire();
			wakeLock.setReferenceCounted(false);
		} else if (wakeLock.isHeld()) {
			Log.d(TAG, "We already have a wakelock held, do nothing");
		} else {
			Log.e(TAG, "Acquiring new WakeLock on an existing notheld instance");
			wakeLock.acquire();
		}
	}

	public void releaseLock() {

		if (wakeLock != null) {
			// Log.e(TAG, "Releasing Wakelock: " + wakeLock.toString());
			if (wakeLock.isHeld()) {
				Log.d(TAG, "a Wakelock is held and being released now");
				wakeLock.release();
			} /* else Log.d(TAG, "Wakelock not held"); */
		}
		/*
		 * else Log.w(TAG, "Wakelock was null");
		 */
	}

}